import { Http } from "@/network/Http";
import { useEffect, useMemo, useState } from "react";
import { IArticleInfo, IUseArticleInfoOptions, getArticleInfo } from "./useArticleInfo";

export interface IArticleDetail extends IArticleInfo {
  content: string;
}
export interface IGetArticleDetailOptions {
  article_id?: string | number;
  also?: 'html' | 'markdown';
}
export async function getArticleDetail(article_id: undefined, ac?: AbortController): Promise<undefined>;
export async function getArticleDetail(article_id: string | number, ac?: AbortController): Promise<IArticleDetail>;
export async function getArticleDetail(article_id: string | number | undefined, ac?: AbortController): Promise<IArticleDetail | undefined>;
export async function getArticleDetail(opts: IGetArticleDetailOptions, ac?: AbortController): Promise<IArticleDetail | undefined>;
export async function getArticleDetail(arg0: string | number | undefined | IGetArticleDetailOptions, ac?: AbortController): Promise<IArticleDetail | undefined> {
  const article_id = typeof arg0 === 'object' ? arg0.article_id : arg0;
  const also = (typeof arg0 === 'object' ? arg0.also : 'markdown') || 'markdown';

  const info = await getArticleInfo(article_id, ac)
  const link = also === 'markdown' ? info?.link : info?.html_link;
  if (!link) return void 0;
  const content = await Http.get(link, void 0, { ...ac }).then(r => r.text())
  return { ...info, content }
}

export interface IUseArticleDetailOptions extends IUseArticleInfoOptions {
  also?: 'html' | 'markdown'
}
export function useArticleDetail(opts: IUseArticleDetailOptions) {
  const { article_id, also } = opts;
  const [loading, set_loading] = useState(false);
  const [data, set_data] = useState<IArticleDetail | undefined>();
  const [error, set_error] = useState<any>(void 0);
  useEffect(() => {
    if (!article_id) return;
    set_loading(true);
    const c = new AbortController();
    getArticleDetail({ article_id, also }, c)
      .then(r => set_data(r))
      .catch(e => set_error(e))
      .finally(() => set_loading(false));
    return () => c.abort();
  }, [article_id, also]);
  return useMemo(() => ({ data, error, loading }), [data, error, loading]);
}
